package xyz.longicorn.driver.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import xyz.longicorn.driver.dao.LoginUserDao;
import xyz.longicorn.driver.pojo.LoginUser;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;


@Component
public class UserRealm extends AuthorizingRealm {
@Resource
    private LoginUserDao loginUserDao;
    // 判断是否支持对应请求token
    @Override
    public boolean supports(AuthenticationToken token) {
        return token != null && token instanceof SimpleHeaderToken;
    }

    // 处理授权 获取凭证对该凭证赋权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("用户凭证:" + primaryPrincipal);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Set<String> roleSet = new HashSet<>(); // 角色列表
        roleSet.add("user");
        roleSet.add("vip");
        info.setRoles(roleSet);

        Set<String> permsSet = new HashSet<>(); // 权限列表
        permsSet.add("query-list");
        permsSet.add("upload-file");
        info.setStringPermissions(permsSet);
        return info;
    }

    // 处理认证 验证请求的凭证是否合法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        String credentials = (String) authenticationToken.getCredentials(); // 获取凭证
        System.out.println("用户凭证:" + credentials);
        //TODO 完成token的验证(是否有效) 返回数据库信息

        return new SimpleAuthenticationInfo(credentials, credentials, getName());
    }
}
